#include	<FW/System/Win32/Thread.h>
#include	<process.h>

namespace System
{

	Thread::Thread ( void ) :
		mHandle ( NULL ), mFunction ( NULL ), mUserData ( NULL )
	{
	}

	Thread::Thread ( FuncType Function, void * UserData = NULL ) :
		mHandle ( NULL ), mFunction ( Function ), mUserData ( UserData )
	{
	}

	Thread::~Thread ( void )
	{
		Wait ( );
	}

	void Thread::Start ( void )
	{
		Wait ( );
		mHandle = reinterpret_cast < HANDLE > ( _beginthreadex ( NULL, 0, & Thread::ThreadFunc, this, 0, NULL ) );


		//	if (!mHandle)
		//		std::cerr << "Failed to create thread" << std::endl;
	}

	void Thread::Wait ( void )
	{
		if ( mHandle )
		{
			WaitForSingleObject ( mHandle, INFINITE );
			CloseHandle ( mHandle );
			mHandle = NULL;
		}
	}

	void Thread::Stop ( void )
	{
		if ( mHandle )
		{
			TerminateThread ( mHandle, 0 );
			mHandle = NULL;
		}
	}

	void Thread::Run ( void )
	{
		if ( mFunction )
			mFunction ( mUserData );
	}

	unsigned int __stdcall Thread::ThreadFunc ( void * UserData )
	{
		Thread * ThreadInstance = reinterpret_cast < Thread * > ( UserData );
		ThreadInstance -> Run ( );
		_endthreadex ( 0 );
		return 0;
	}

}
